package com.zycfc.zsf.boot.druid;

import org.apache.commons.codec.binary.*;
import javax.crypto.spec.*;
import javax.crypto.*;
import java.security.*;

public class DESUtil
{
    private static final String ALGORITHM = "DES";
    private static final String UTF_8 = "UTF-8";
    
    public static String decryptHex(final String key, final String textHex) throws Exception {
        return new String(decrypt(Hex.decodeHex(textHex.toCharArray()), key), "UTF-8");
    }
    
    public static String encryptHex(final String key, final String textHex) throws Exception {
        return new String(encrypt(textHex, key), "UTF-8");
    }
    
    public static byte[] encrypt(final String text, final String key) throws Exception {
        final SecretKeySpec securekey = new SecretKeySpec(key.getBytes("UTF-8"), "DES");
        final Cipher cipher = Cipher.getInstance("DES");
        cipher.init(1, securekey);
        return cipher.doFinal(text.getBytes("UTF-8"));
    }
    
    public static byte[] decrypt(final byte[] data, final String key) throws Exception {
        return decrypt(data, key.getBytes("UTF-8"));
    }
    
    public static byte[] decrypt(final byte[] data, final byte[] key) throws Exception {
        final SecretKeySpec securekey = new SecretKeySpec(key, "DES");
        final Cipher cipher = Cipher.getInstance("DES");
        cipher.init(2, securekey);
        return cipher.doFinal(data);
    }
}
